package org.example.jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

public class JDBCReg {
    public static void main(String[] args) {
        try (Connection connection=DBUtil.getConnection();){
            //接收用户输入;
            Scanner scanner=new Scanner(System.in);
            System.out.println("请输入用户名:");
            String username=scanner.nextLine();
            System.out.println("请输入密码:");
            String password=scanner.nextLine();
            System.out.println("请输入昵称:");
            String nickname=scanner.nextLine();
            System.out.println("请输入年龄:");
            int age=scanner.nextInt();
            String sql1="SELECT id FROM userinfo WHERE username=? ";
            PreparedStatement ps1=connection.prepareStatement(sql1);
            ps1.setString(1,username);
            ResultSet rs1=ps1.executeQuery();
            if(rs1.next()){//被占用
                System.out.println("该用户名被占用,请换一个");
            }else {//未被占用
            String sql="INSERT INTO user (username,password,nickname,age) VALUES (?,?,?,?)";
            PreparedStatement ps2=connection.prepareStatement(sql);
            ps2.setString(1,username);
            ps2.setString(2,password);
            ps2.setString(3,nickname);
            ps2.setInt(4,age);
            ps2.executeUpdate();

            int i=ps2.executeUpdate();
            if (i>0){
                System.out.println("恭喜您,注册成功");
            }else {
                System.out.println("系统繁忙,请稍后再试");
            }
            }

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
